import util from '@/libs/util';
import Cookies from 'js-cookie';
import domtoimage from 'dom-to-image';
import CONSTANTS from '@/config/constants';
import DragDropContainer from '../prizemodel/dragDropContainer/dragDropContainer.vue'

// console.log(utils)

export default {
    name: 'exportable-table',
    components: { DragDropContainer },
    data() {
        return {
            baseuser: JSON.parse(Cookies.get('baseUser')),
            formData: {
                perNum: 1,
                pattern: null
            },
            themeList: [],
            theme: [],
            modelList: [],
            allMember: [],
            makeTemplate: {
                backgroundUrl: '',
                sprites: []
            },
            imgScale: 1,
            $previewContainer: null,
            SERVER_HOST: CONSTANTS.SERVER_HOST,
            picMaxHeight: '2105px', // 29.7cm
            picMaxWidth: '1488px', // 21.0cm
            numList: [1, 2, 3, 4, 5, 6, 7, 8, 9],
            diplomasList: []
        };
    },
    mounted() {
        this.loadModal();
        this.loadTheme();

        window.addEventListener('resize', this.onResize)
        this.onResize()
    },
    methods: {
        loadModal() {
            util.ajax.post('/busine/model/findAll', util.toFormData({
                organizeid: (this.baseuser.type === 2 ? this.baseuser.orgId : '')
            })).then(res => {
                this.modelList = res.data.data;
            });
        },
        loadTheme() {
            util.ajax.post('/busine/theme/findAll', util.toFormData({
                organizeid: (this.baseuser.type === 2 ? this.baseuser.orgId : '')
            })).then(res => {
                let themeList = [];
                let allTheme = res.data.data;
                allTheme.forEach((item, index) => {
                    if (item.level === 1) {
                        let childernList = [];
                        allTheme.forEach((citem, index) => {
                            if (citem.level === 2 && citem.parentId === item.id) {
                                childernList.push({
                                    value: citem.id,
                                    label: citem.name
                                });
                            }
                        });
                        themeList.push({
                            value: item.id,
                            label: item.name,
                            children: childernList
                        });
                    }
                });
                this.themeList = themeList;
            });
        },
        modelChange() {
            console.log('MODEL CHANGE')
            this.allMember = [];
            this.theme = [];
            this.formData.themeid = '';
            let content = '';
            this.modelList.forEach((item) => {
                if (item.id === this.formData.modelid) content = item.content;
            });
            if (content) {
                this.makeTemplate = JSON.parse(content);
                // this.setScale();
            } else {
                this.makeTemplate = {
                    backgroundUrl: '',
                    sprites: []
                };
                this.imgScale = 1;
            }
        },
        setTheme(labels) {
            const index = labels.length - 1;
            return labels[index];
        },
        themeChangeMore(value, selectData) {
            const index = value.length - 1;
            this.formData.themeid = value[index];
            this.replaceText('theme', selectData[index].label);
            this.loadMemberByTheme();
        },
        loadMemberByTheme() {
            this.allMember = [];
            if (this.formData.themeid !== '') {
                util.ajax.post('/busine/theme/member/getMemberByTheme', util.toFormData({
                    themeId: this.formData.themeid,
                    prizeFlag: '1'
                })).then(res => {
                    let data = res.data.data.list;
                    data.forEach((item) => {
                        this.allMember.push({
                            key: item.id,
                            label: item.member.realname + '-' + item.member.phone,
                            name: item.team ? item.team : item.member.realname,
                            memberId: item.memberId,
                            spare1: item.spare1,
                            spare2: item.spare2,
                            spare3: item.spare3,
                            diplomasId: item.diplomasId,
                            diplomas: item.diplomas.name,
                            school: item.member.school
                        });
                    });
                });
            }
        },
        replaceText(name, text) {
            let currSprite = this.makeTemplate.sprites;
            var objE = document.createElement('div');
            currSprite.forEach((item, index) => {
                if (item.name === name) {
                    objE.innerHTML = item.content;
                    // objE.getElementsByTagName('span')[0].innerHTML = text;
                    util.updateInnermostText(objE, text)
                    this.$refs.dndContainer.updateSpriteTextByName(item.name, objE.innerHTML)
                }
            });
        },
        save() {
            if (!this.formData.modelid) {
                this.$Modal.error({
                    title: '',
                    content: '请选择模板！'
                });
                return;
            }
            if (!this.formData.themeid) {
                this.$Modal.error({
                    title: '',
                    content: '请选择主题！'
                });
                return;
            }
            if (this.allMember.length === 0) {
                this.$Modal.error({
                    content: '该主题下没有会员！'
                });
                return;
            }
            this.$Spin.show({
                render: (h) => {
                    return h('div', [
                        h('Icon', {
                            'class': 'demo-spin-icon-load',
                            props: {
                                type: 'load-c',
                                size: 30
                            }
                        }),
                        h('div', '奖状生成中请稍等...')
                    ]);
                }
            });
            this.makePrize(this.allMember[0], 0);
        },
        makePrize(item, index) {
            let sprites = this.makeTemplate.sprites;
            let image = this.$refs.dndContainer.$image;
            let formData = this.formData;
            formData.membeid = item.memberId;
            formData.diplomasid = item.diplomasId;
            formData.orgid = this.baseuser.orgId;
            let haveQRcode = false;
            sprites.forEach((citem) => {
                if (citem.name && citem.name === 'QRcode') {
                    haveQRcode = true;
                }
            });
            util.ajax.post('/busine/prizes/save', util.toFormData(formData)).then(res => {
                let prizeId = res.data.data;
                var objE = document.createElement('div');
                if (haveQRcode) {
                    util.ajax.post('/qRcode/qRcode', util.toFormData({
                        prizeId: prizeId
                    })).then((qrRes) => {
                        if (qrRes.data.message === 'SUCCESS') {
                            let QRcode = qrRes.data.data;
                            sprites.forEach((citem, index) => {
                                objE.innerHTML = citem.content;
                                if (citem.name && citem.name === 'name') {
                                    var perNum = this.formData.perNum;
                                    var nameList = item.name.split('、');
                                    var name = '';
                                    for (var i = 0; i < nameList.length; i++) {
                                        if (i > 0) {
                                            if (i % perNum === 0) {
                                                name += '<br>';
                                            } else {
                                                name += '、';
                                            }
                                        }
                                        name += nameList[i];
                                    }
                                    // objE.getElementsByTagName('span')[0].innerHTML = name;
                                    util.updateInnermostText(objE, name)
                                    this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);
                                } else if (citem.name && citem.name === 'QRcode') {
                                    citem.imageSrc = this.SERVER_HOST + QRcode;
                                } else if (citem.name && citem.name !== 'theme') {
                                    // objE.getElementsByTagName('span')[0].innerHTML = item[citem.name];
                                    util.updateInnermostText(objE, item[citem.name])
                                    this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);                                    // citem.text = item[citem.name];
                                }
                            });
                            this.toPicture(image, index, prizeId);
                        } else {
                            this.$Message.warning(qrRes.data.message || '未知错误！');
                            util.ajax.post('/busine/prizes/delete', util.toFormData({
                                id: prizeId
                            }));
                        }
                    });
                } else {
                    sprites.forEach((citem) => {
                        objE.innerHTML = citem.content;
                        if (citem.name && citem.name === 'name') {
                            var perNum = this.formData.perNum;
                            var nameList = item.name.split('、');
                            var name = '';
                            for (var i = 0; i < nameList.length; i++) {
                                if (i > 0) {
                                    if (i % perNum === 0) {
                                        name += '<br>';
                                    } else {
                                        name += '、';
                                    }
                                }
                                name += nameList[i];
                            }
                            // objE.getElementsByTagName('span')[0].innerHTML = name;
                            util.updateInnermostText(objE, name)
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML)
                        } else if (citem.name && citem.name !== 'theme') {
                            // objE.getElementsByTagName('span')[0].innerHTML = item[citem.name];
                            util.updateInnermostText(objE, item[citem.name])
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML)
                        }
                    });
                    this.toPicture(image, index, prizeId);
                }
            });
        },
        toPicture(image, index, prizeId) {
            this.$nextTick().then(() => {
                const done = this.$refs.dndContainer.capture()
                domtoimage.toPng(image, {
                    quality: 1
                }).then((dataUrl) => {
                    done()
                    util.ajax.post('/upload/uploadPrize', util.toFormData({
                        dataUrl: dataUrl
                    })).then(imgRes => {
                        if (imgRes.data.message === 'SUCCESS') {
                            util.ajax.post('/busine/prizes/save', util.toFormData({
                                id: prizeId,
                                imgpath: imgRes.data.data.imgPath
                            })).then(() => {
                                if (index + 1 >= this.allMember.length) {
                                    this.$Message.success('奖状生成完成！');
                                    this.$Spin.hide();
                                } else {
                                    this.makePrize(this.allMember[index + 1], index + 1);
                                }
                            });
                        } else {
                            this.$Message.warning(imgRes.data.message || '未知错误！');
                            util.ajax.post('/busine/prizes/delete', util.toFormData({
                                id: prizeId
                            }));
                        }
                    });
                });
            });
        },
        reset() {
            this.theme = [];
            this.modelChange();
        },
        onResize() {
            const rect = this.$el.getBoundingClientRect();
            this.$refs.dndContainer.applyContainerSize(rect.width - 600, rect.height)
        },
        themeChangeOne(value, selectData) {
            const index = value.length - 1;
            this.formData.themeid = value[index];
            this.replaceText('theme', selectData[index].label);
            this.loadDiploma();
        },
        loadDiploma() {
            util.ajax.post('/busine/diplomas/findByTheme', util.toFormData({
                themeId: this.formData.themeid
            })).then(res => {
                this.diplomasList = res.data.data;
            });
        },
        dipChange(data) {
            this.replaceText('diplomas', data.label);
            this.loadMember(data.value);
        },
        loadMember(diplomasId) {
            this.allMember = [];
            if (this.formData.themeid !== '') {
                util.ajax.post('/busine/theme/member/getMember', util.toFormData({
                    themeId: this.formData.themeid,
                    diplomasId: diplomasId
                })).then(res => {
                    let data = res.data.data;
                    data.forEach((item) => {
                        this.allMember.push({
                            key: item.id,
                            label: item.member.realname + '-' + item.member.phone,
                            name: item.team ? item.team : item.member.realname,
                            memberId: item.memberId,
                            spare1: item.spare1,
                            spare2: item.spare2,
                            spare3: item.spare3,
                            diplomasId: item.diplomasId,
                            diplomas: item.diplomas.name,
                            school: item.member.school
                        });
                    });
                });
            }
        },
        memberChange() {
            this.allMember.forEach(item => {
                if (this.formData.memberId === item.key) {
                    let sprites = this.makeTemplate.sprites;
                    var objE = document.createElement('div');
                    // debugger
                    sprites.forEach((citem) => {
                        objE.innerHTML = citem.content;
                        if (citem.name && citem.name === 'name') {
                            var perNum = this.formData.perNum;
                            var nameList = item.name.split('、');
                            var name = '';
                            for (var i = 0; i < nameList.length; i++) {
                                if (i > 0) {
                                    if (i % perNum === 0) {
                                        name += '<br>';
                                    } else {
                                        name += '、';
                                    }
                                }
                                name += nameList[i];
                            }
                            // objE.getElementsByTagName('span')[0].innerHTML = name;
                            util.updateInnermostText(objE, name)
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);
                        } else if (citem.name && citem.name !== 'theme') {
                            // objE.getElementsByTagName('span')[0].innerHTML = item[citem.name];

                            console.log('=====')
                            console.log(objE)
                            console.log(item[citem.name])
                            util.updateInnermostText(objE, item[citem.name])
                            console.log('-----')
                            console.log(objE.innerHTML)
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);
                        }
                    });
                }
            });
        },
        numChange() {
            this.allMember.forEach(item => {
                if (this.formData.memberId === item.key) {
                    let sprites = this.makeTemplate.sprites;
                    var objE = document.createElement('div');
                    sprites.forEach((citem) => {
                        if (citem.name && citem.name === 'name') {
                            objE.innerHTML = citem.content;
                            var perNum = this.formData.perNum;
                            var nameList = item.name.split('、');
                            var name = '';
                            for (var i = 0; i < nameList.length; i++) {
                                if (i > 0) {
                                    if (i % perNum === 0) {
                                        name += '<br>';
                                    } else {
                                        name += '、';
                                    }
                                }
                                name += nameList[i];
                            }
                            // objE.getElementsByTagName('span')[0].innerHTML = name;
                            util.updateInnermostText(objE, name)
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);
                        }
                    });
                }
            });
        },
        saveOne() {
            if (!this.formData.memberId) {
                this.$Modal.error({
                    title: '',
                    content: '请选择需要生成奖状的会员！'
                });
                return;
            }
            this.$Spin.show({
                render: (h) => {
                    return h('div', [
                        h('Icon', {
                            'class': 'demo-spin-icon-load',
                            props: {
                                type: 'load-c',
                                size: 30
                            }
                        }),
                        h('div', '奖状生成中请稍等...')
                    ]);
                }
            });
            let sprites = this.makeTemplate.sprites;
            let image = this.$refs.dndContainer.$image;
            let formData = this.formData;
            this.allMember.forEach(item => {
                if (item.key === this.formData.memberId) {
                    formData.membeid = item.memberId;
                }
            })
            formData.diplomasid = this.formData.diplomasId;
            formData.orgid = this.baseuser.orgId;
            let haveQRcode = false;
            sprites.forEach((citem) => {
                if (citem.name && citem.name === 'QRcode') {
                    haveQRcode = true;
                }
            });

            /* console.log(Object.assign(
                {}, formData, {
                    pattern: formData.pattern === 1
                }
            ))
            return */

            util.ajax.post('/busine/prizes/save', util.toFormData(Object.assign(
                {}, formData, {
                    pattern: formData.pattern === 1
                }
            ))).then(res => {
                let prizeId = res.data.data;
                var objE = document.createElement('div');
                if (haveQRcode) {
                    util.ajax.post('/qRcode/qRcode', util.toFormData({
                        prizeId: prizeId
                    })).then((qrRes) => {
                        if (qrRes.data.message === 'SUCCESS') {
                            let QRcode = qrRes.data.data;
                            sprites.forEach((citem, index) => {
                                objE.innerHTML = citem.content;
                                if (citem.name && citem.name === 'QRcode') {
                                    citem.imageSrc = this.SERVER_HOST + QRcode;
                                }
                            });
                            this.toPictureOne(image, prizeId);
                        } else {
                            this.$Message.warning(qrRes.data.message || '未知错误！');
                            util.ajax.post('/busine/prizes/delete', util.toFormData({
                                id: prizeId
                            }));
                        }
                    });
                } else {
                    this.toPictureOne(image, prizeId);
                }
            });
        },
        toPictureOne(image, prizeId) {
            this.$nextTick().then(() => {
                const done = this.$refs.dndContainer.capture()
                domtoimage.toPng(image, {
                    quality: 1
                }).then((dataUrl) => {
                    done()
                    util.ajax.post('/upload/uploadPrize', util.toFormData({
                        dataUrl: dataUrl
                    })).then(imgRes => {
                        if (imgRes.data.message === 'SUCCESS') {
                            util.ajax.post('/busine/prizes/save', util.toFormData({
                                id: prizeId,
                                imgpath: imgRes.data.data.imgPath
                            })).then(() => {
                                this.$Message.success('奖状生成完成！');
                                this.$Spin.hide();
                            });
                        } else {
                            this.$Message.warning(imgRes.data.message || '未知错误！');
                            util.ajax.post('/busine/prizes/delete', util.toFormData({
                                id: prizeId
                            }));
                        }
                    });
                });
            });
        }
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.onResize);
    }
};
